<template>
  <div id="lyric-view">
    <div class="music-disk">
      <div class="changzhen pointer" :class="{ 'zhen-rotato': rotato }">
        <img src="../../assets/images/changzhen.png">
      </div>
      <!-- 唱片 -->
      <div class="changpian-outside" :class="{ 'animation-rotato': rotato }">
        <div class="changpian-inside">
          <img :src="recordImg">
        </div>
      </div>
    </div>
    <!-- 歌词信息 -->
    <!-- 
      @scroll="scrollLyric" -->
    <div
      class="lyric-list"
      @mouseenter="showScroll"
      @mouseleave="hiddenScroll"
    >
      <ul ref="lyricUl" v-if="!isLoad" @click="handlerChangeTime">
        <li
          class="lyric-item"
          ref="lyricItem"
          v-for="(item, index) in lyriclist"
          :key="item.id"
          :data-index="index"
          :data-time="item.time"
          :class="{ 'current': index === lyricIndex }"
        >
          <!-- <span> -->
            {{ item.lyricText }}

          <!-- </span> -->
          <!-- <span v-if="item.fanyiText">{{ item.fanyiText }}</span> -->
        </li>
        <!-- 滚动歌词贡献者 -->
        <div class="contri-user" v-show="islyricUser">
          滚动歌词贡献者：
          <span class="pointer" style="text-decoration: underline;" @click="goUserDetail(lyricUser.userid)">
            {{ lyricUser.nickname }}
          </span>
        </div>
        <div class="contri-user mtop-10" v-show="istransUser">
          翻译贡献者：
          <span class="pointer" style="text-decoration: underline;" @click="goUserDetail(transUser.userid)">
            {{ transUser.nickname }}
          </span>
        </div>
        
        <!-- <div class="left-line"></div><div class="right-line"></div> -->
      </ul>
      <LoadingMore
        :domClass="style"
        v-else
      />
    </div>
    <!-- 关联信息,不知道有没有接口 -->
    <div
      class="relevance-info mleft-20"
      @mouseenter="showScroll"
      @mouseleave="hiddenScroll"
    >
      <div
        class="root-in text-hidden pointer mbottom-10"
        title="播放来源：今天从《The Story Never Ends (Piano Version)》"
      >
        播放来源：今天从《The Story Never Ends (Piano Version)》>
      </div>
      <div class="include-list">
        <div class="font-weight">包含这首歌的歌单</div>
        <ul>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
        </ul>
      </div>
      <div class="include-list">
        <div class="font-weight">包含这首歌的歌单</div>
        <ul>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
          <li class="include-item">
            <img v-lazy="'http://p3.music.126.net/BR_ETn4YsHtvDwIJbwK2KA==/109951165806258437.jpg'">
            <span>【旋律控】 超级好听的欧美良曲</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import { throttle, debounce } from '@/utils/optimize'
import LoadingMore from '@/components/Library/LoadingMore';

export default {
  name: 'LyricView',

  components: {
    LoadingMore
  },

  inject: ['isRotato', 'timeChange', 'isModal', 'changeTime'],

  props: {
    // 唱片图片
    recordImg: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      lyriclist: [],
      // 存储当前歌词索引值
      lyricIndex: 0,
      // 滚动歌词贡献者
      lyricUser: {},
      // 翻译歌词贡献者
      transUser: {},
      frameId: null,
      // 停止自动滚动
      cancel: false,
      // 判断index是否一样
      // isSame: false,
      style: {
        position: 'absolute',
        width: '100%',
        height: '100%',
        top: '50%',
        left: '50%',
        transform: 'translateX(-50%)'
      }
    };
  },

  computed: {
    rotato() {
      return this.isRotato();
    },
    currentTime() {
      return this.timeChange();
    },
    islyricUser() {
      return this.lyricUser && Object.keys(this.lyricUser).length;
    },
    istransUser() {
      return this.transUser && Object.keys(this.transUser).length;
    },
    ...mapState({
      lyricObj: state => state.detail.lyricObj,
      // 控制切换歌曲的歌词loading
      isLoad: state => state.main.isLoad
    })
  },

  watch: {
    lyricObj: {
      handler(value) {
        if (value && Object.keys(value).length) {
          // 如果存储歌词的array有值,先进行重置操作
          if (this.lyriclist && this.lyriclist.length) {
            this.lyriclist = [];
          }
          // 获取贡献者信息
          if (value.lyricUser) {
            this.lyricUser = value.lyricUser;
          } else {
            this.lyricUser = [];
          }
          if (value.transUser) {
            this.transUser = value.transUser;
          } else {
            this.transUser = [];
          }
          // 先用\n对数据进行拆分成数组
          const lyricList = value.lrc.lyric.split('\n');
          // 是否有翻译
          // let fanyiList = null;
          // console.log(value.tlyric);
          // if (value.tlyric && Object.keys(value.tlyric).length) {
          //   fanyiList = value.tlyric.lyric.split('\n');
          // } else {
          //   fanyiList = null;
          // }
          const regTime = /\[\d{2}:\d{2}.\d{2,3}\]/;
          
          const list = [];
          lyricList.forEach((item, index) => {
            const lyricTime = item.match(regTime);
            // 蠢!!不太明白这里为什么需要判断一下,不判断会报错??
            if (lyricTime && lyricTime.length) {
              // 拿到01:46.253的字符串进行时间格式转换
              const timeStr = lyricTime[0].replace(/\[|]/g,'').split(':');
              // 获取秒数并转成数字
              const secNum = timeStr[1].split('.');
              const sec = parseInt(timeStr[0] * 60 + Number(secNum[0]));
              list.push({
                lyricText: item.split(']')[1].trim(),
                // fanyiText: fanyiList && fanyiList.length ? fanyiList[index].split(']')[1].trim() : '',
                time: `${sec}.${secNum[1]}`,
                id: Math.random().toString().slice(-6)
              })
            }
          });
          this.lyriclist = list;
        }
      }
    },
    currentTime: {
      handler(value) {
        // 这里需要进行判断,只有当有lyriclist时,才进行后续操作。不然会报错
        if (this.lyriclist && this.lyriclist.length) {
          const index = this.lyriclist.findIndex((item, idx) => {
            // console.log('idx', idx)
            // 需要增加一个判断,不然到最后一个索引会持续报错,因为已经是最后一个了
            // console.log(value >= +this.lyriclist[this.lyriclist.length - 1].time, value, '123');
            if (value >= +this.lyriclist[this.lyriclist.length - 1].time) {
              return this.lyriclist.length - 1;
            }
            // 这里进行判断currentTime如果在前句歌词时间和后句歌词之间,返回这句歌词索引。
            // 注意：不能单纯判断+item.time === value,不准确
             if (+item.time < value && +this.lyriclist[idx + 1].time > value) {
              return idx;
            }
          });
          if (index === this.lyricIndex) return;
          // -1时需要重新开始滚动
          if (index === -1) {
            this.handlerChange(0);
          } else if (index === 0) {
            this.handlerChange(this.lyriclist.length - 1);
          } else {
            this.handlerChange(index);
          }
        }
      }
    },
    // lyricIndex: {
    //   handler(value, oldValue) {
    //     console.log(value, oldValue)
    //     if (value === oldValue) {
    //       this.isSame = true;
    //     } else {
    //       this.isSame = false;
    //     }
    //   }
    // }
  },

  methods: {
    // 鼠标移入显示滚动条
    showScroll(event) {
      const classList = event.target.classList;
      classList.add('scroll');
      this.cancel = true;
      window.cancelAnimationFrame(this.frameId);
    },
    // 鼠标移出隐藏滚动条
    hiddenScroll(event) {
      const classList = event.target.classList;
      classList.remove('scroll');
      // if (!this.cancel) clearTimeout(timer);
      // let timer = setTimeout(() => {
        this.cancel = false;
      // }, 2000);
    },
    // 滚动歌词
    // scrollLyric(e) {
    //   // console.log('开始！', e, document.querySelector('.left-line').style);
    //   // document.querySelector('.left-line').style.top =  this.lyricIndex * 45;
    //   // document.querySelector('.right-line').style.top =  this.lyricIndex * 45;
    // },
    // 执行动画函数,index为索引值
    animationFn(index) {
      let start
      const step = timestamp => {
        if (start === undefined) start = timestamp;
        const elapsed = timestamp - start;
        const li = this.$refs.lyricItem[index] ? this.$refs.lyricItem[index].offsetHeight : 45;
        if (index === 0) {
          document.querySelector('.lyric-list').scrollTop = 0;
          return;
        }
        // if (this.lyriclist[index].fanyiText && li) {
        //   document.querySelector('.lyric-list').scrollTop = li * index;
        // } else 
        // console.log(this.isSame)
        if (li && li >= 45) {
          document.querySelector('.lyric-list').scrollTop = 45 * index;
        }
        // console.log(document.querySelector('.lyric-list').scrollTop);
        
        if (elapsed < 300) {
          this.frameId =  window.requestAnimationFrame(step);
        }
      }
      this.frameId = window.requestAnimationFrame(step);
    },
    handlerChange(v) {
      this.lyricIndex = v;
      this.$nextTick(() => {
        if (!this.cancel) {
          this.animationFn(v);
        }
      })
    },
    handlerChangeTime: debounce(function(event) {
      const chun = this.lyriclist
        .findIndex(item => item.lyricText.includes('纯音乐'));
      if (chun !== -1) return;
      // event.stopPropagation();
      const { time, index } = event.target.dataset;
      if (index && !this.rotato) {
        this.$refs.lyricItem.
          forEach(item => {
            if (item.classList[1] === 'current') {
              item.classList.remove('current');
            }
          });
        this.$refs.lyricItem[index].classList.add('current');
      }
      this.changeTime(+time);
    }, 500),
    // 跳转至用户页
    goUserDetail(id) {
      this.$router.push({
        name: 'userdetail',
        query: { id }
      });
      // 祖辈组件传递过来的显示隐藏弹框的函数
      this.isModal(false);
    }
  }
};
</script>

<style lang="less" scoped>
#lyric-view {
  height: calc(100% - 165px);
  // &::after {
  //   position: absolute;
  //   content: '';
  //   width: 100%;
  //   height: 100%;
  //   top: 0;
  //   left: 0;
  //   box-shadow: 0 0px 30px 50px #f8f6f7 inset;
  // }
  .music-disk {
    position: relative;
    float: left;
    .changzhen {
      position: absolute;
      top: -35px;
      left: 50%;
      width: 120px;
      transform-origin: 3px 3px;
      transition: all .5s;
      z-index: 20;
    }
    .changpian-outside {
      margin-top: 40px;
      width: 300px;
      height: 300px;
      border-radius: 50%;
      background-color: #c4c3c6;
      display: flex;
      justify-content: center;
      align-items: center;
      .changpian-inside {
        width: 270px;
        height: 270px;
        background-color: #1a1c1e;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        >img {
          width: 180px;
          height: 180px;
          border-radius: 50%;
        }
      }
    }
    .zhen-rotato {
      transform: rotate(35deg);
    }
    .animation-rotato {
      @keyframes recordrotato
      {
        from {
          transform: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }

      @-webkit-keyframes recordrotato /*Safari and Chrome*/
      {
        from {
          transform: rotate(0deg);
        }
        to {
          transform: rotate(360deg);
        }
      }
      animation: recordrotato 30s linear infinite;
    }
  }
  .lyric-list {
    position: relative;
    width: 380px;
    height: 380px;
    float: left;
    text-align: center;
    overflow: hidden;
    >ul {
      // 将ul脱离文档流,防止重排
      position: absolute;
      width: 100%;
      padding: 190px 0;
      .lyric-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        // position: relative;
        // padding: 12px 0;
        height: 45px;
        line-height: 45px;
        color: #1a1c1e;
      }
      .contri-user {
        color: #909399;
      }
      .current {
        color: #000;
        font-weight: 700;
        font-family: emoji;
        transition: all .5s;
      }
      .left-line {
        position: absolute;
        top: 50%;
        left: 10px;
        height: 1px;
        width: 20%;
        background-image: linear-gradient(to right, #6a6363, #ccc);
        transform: translateY(-50%);
      }
      .right-line {
        position: absolute;
        top: 50%;
        right: 10px;
        height: 1px;
        width: 20%;
        background-image: linear-gradient(to right, #ccc, #6a6363);
        transform: translateY(-50%);
      }
    }
  }
  .relevance-info {
    float: right;
    width: 260px;
    height: 300px;
    overflow: hidden;
    padding-right: 10px;
    .root-in:hover {
      color: #2e2ecd;
    }
    .include-list {
      .include-item {
        height: 40px;
        line-height: 40px;
        >img {
          width: 30px;
          height: 30px;
          border-radius: 5px;
        }
      }
    }
  }
  .scroll {
    // 解决滚动条占位闪烁问题
    overflow-y: overlay;
  }
}
</style>